<!--
 * @Author: 谢陈洁
 * @Date: 2025-06-19 08:52:51
 * @LastEditors: 谢陈洁
 * @LastEditTime: 2025-08-01 16:29:17
 * @Description: file content
-->
<template>
  <div class="page">
    <el-card class="table-card">
      <div class="action-box">
        <add-button v-permission="'role:add'" @click="openDialog()">添加角色</add-button>
      </div>
      <ProTable
        :columns="columns"
        :data="roles"
        :pagination="pagination"
        showIndex
        :loading="loading"
        @pagination-change="handlePaginationChange"
      >
        <template #action="{ row }">
          <!-- <base-button icon="User" size="small" @click="openDrawerWithRoleId(row.id)">
            分配权限
          </base-button> -->
          <edit-button size="small" v-permission="'role:edit'" @click="openDialog(row)">
            编辑
          </edit-button>
          <del-button size="small" v-permission="'role:delete'" @click="handleDelete(row.id)">
            删除
          </del-button>
        </template>
      </ProTable>
    </el-card>
    <base-drawer
      title="编辑角色"
      width="400px"
      v-model="dialogVisible"
      @cancel="closeDialog"
      @ok="handleSubmit"
    >
      <DynamicForm
        ref="formRef"
        :form-config="newFormConifg"
        v-model="formData"
        @submit-success="handleSubmitSuccess"
        label-width="120px"
      />
    </base-drawer>
  </div>
</template>
<script setup lang="ts">
  import { saveRole, deleteRole } from '@/services/apis/system/role'
  import { columns, editFormConfig } from './config'
  import { usePermissionStore } from '@/stores/permission'
  import { storeToRefs } from 'pinia'
  import { useDeleteConfirm, useFormDialog, useTableData } from '@/hooks'
  const permissionStore = usePermissionStore()
  const { roles, permissions } = storeToRefs(permissionStore)
  // 表格相关配置
  const { pagination, fetchData, handlePaginationChange, loading } = useTableData(
    permissionStore.getRoles
  )

  const newFormConifg = computed(() => {
    const item = editFormConfig.find(item => {
      return item.prop === 'permissions'
    })
    if (item?.attrs) {
      item.attrs.data = permissions.value
    }
    console.log(item, 'item', editFormConfig, 'editFormConfig')
    return editFormConfig
  })
  // 表单编辑弹框配置
  const {
    openDialog,
    closeDialog,
    formData,
    formRef,
    dialogVisible,
    handleSubmit,
    handleSubmitSuccess
  } = useFormDialog(saveRole, permissionStore.getRoles)
  // 删除
  const { handleDelete } = useDeleteConfirm(deleteRole, permissionStore.getRoles)

  onMounted(() => {
    fetchData()
    permissionStore.getPermissions()
  })
</script>
<style lang="scss" scoped></style>
